package com.zbkj.service.service.course.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.model.course.Course;
import com.zbkj.common.model.course.CourseDescription;
import com.zbkj.common.model.course.CourseList;
import com.zbkj.common.model.course.CourseListStudyLog;
import com.zbkj.common.model.system.SystemAttachment;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.course.CourseListRequest;
import com.zbkj.common.request.course.CourseListSearchRequest;
import com.zbkj.common.response.CommonResult;
import com.zbkj.common.response.course.CourseListResponse;
import com.zbkj.common.response.course.CourseListStudyLogResponse;
import com.zbkj.service.dao.CourseListDao;
import com.zbkj.service.service.SystemAttachmentService;
import com.zbkj.service.service.UserService;
import com.zbkj.service.service.course.CourseDescriptionService;
import com.zbkj.service.service.course.CourseListService;
import com.zbkj.service.service.course.CourseListStudyLogService;
import com.zbkj.service.service.course.CourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author Mr.Zhang
 * @description CourseListServiceImpl 接口实现
 * @date 2022-07-22
 */
@Service
public class CourseListServiceImpl extends ServiceImpl<CourseListDao, CourseList> implements CourseListService {

    @Resource
    private CourseListDao dao;

    @Autowired
    private SystemAttachmentService attachmentService;

    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseDescriptionService courseDescriptionService;

    @Autowired
    private UserService userService;

    @Autowired
    private CourseListStudyLogService courseListStudyLogService;
    /**
     * 列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<CourseList>
     * @author Mr.Zhang
     * @since 2022-07-22
     */
    @Override
    public List<CourseList> getList(CourseListSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 CourseList 类的多条件查询
        LambdaQueryWrapper<CourseList> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CourseList::getCourseId, request.getCourseId());
        lambdaQueryWrapper.orderByAsc(CourseList::getSort);
        return dao.selectList(lambdaQueryWrapper);
    }

    @Override
    public List<CourseList> getListFront(CourseListSearchRequest request, PageParamRequest pageParamRequest) {
        //todo
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> add(CourseListRequest request) {
        CourseList courseList = new CourseList();
        BeanUtils.copyProperties(request, courseList);
        courseList.setCreateTime(new Date());
        if (ObjectUtil.isNotEmpty(request.getImageAttId())) {
            SystemAttachment attachment = attachmentService.getById(request.getImageAttId());
            courseList.setImage(attachment.getSattDir());
        }
        // 更新课程的章节数
        LambdaUpdateWrapper<Course> courseLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        courseLambdaUpdateWrapper.setSql(StrUtil.format("list_count = list_count + {}", 1));
        courseLambdaUpdateWrapper.eq(Course::getId, request.getCourseId());
        courseService.update(courseLambdaUpdateWrapper);
        save(courseList);

        CourseDescription courseDescription=new CourseDescription();
        courseDescription.setDescription(request.getDescription().length() > 0 ? attachmentService.clearPrefix(request.getDescription()) : "");
        courseDescription.setType(Constants.COURSE_DESCRIPTION_TYPE_LIST);
        courseDescription.setLinkId(courseList.getId());
        courseDescriptionService.save(courseDescription);

        return CommonResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> update(CourseListRequest courseListRequest) {
        CourseList courseList = new CourseList();
        BeanUtils.copyProperties(courseListRequest, courseList);
        if (ObjectUtil.isNotEmpty(courseListRequest.getImageAttId())) {
            SystemAttachment attachment = attachmentService.getById(courseListRequest.getImageAttId());
            courseList.setImage(attachment.getSattDir());
        }

        courseDescriptionService.deleteById(Constants.COURSE_DESCRIPTION_TYPE_LIST,courseList.getId());
        CourseDescription courseDescription=new CourseDescription();
        courseDescription.setDescription(courseListRequest.getDescription().length() > 0
                ? attachmentService.clearPrefix(courseListRequest.getDescription()) : "");
        courseDescription.setType(Constants.COURSE_DESCRIPTION_TYPE_LIST);
        courseDescription.setLinkId(courseList.getId());
        courseDescriptionService.save(courseDescription);

        if (updateById(courseList)) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    @Override
    public CourseListResponse detailFront(Integer courseListId) {
        Integer uid=userService.getUserId();
        //todo
        CourseList courseList=getById(courseListId);
        CourseListResponse courseListResponse=new CourseListResponse();
        BeanUtil.copyProperties(courseList,courseListResponse);
        if(uid.equals(0)){
            return courseListResponse;
        }
        //登录用户 获取其课程章节的个人信息：学习进度等
        LambdaQueryWrapper<CourseListStudyLog> lqw=new LambdaQueryWrapper<>();
        lqw.eq(CourseListStudyLog::getCourseListId,courseListId);
        lqw.eq(CourseListStudyLog::getUid,uid);
        CourseListStudyLog studyLog= courseListStudyLogService.getOne(lqw);
        if(ObjectUtil.isNull(studyLog)){
            return courseListResponse;
        }
        courseListResponse.setStudyLength(studyLog.getStudyLength());
        courseListResponse.setUid(studyLog.getUid());
        courseListResponse.setStatus(studyLog.getStatus());
        courseListResponse.setCourseListStudyLogId(studyLog.getId());
        //获取富文本详情
        LambdaQueryWrapper<CourseDescription> dlqw=new LambdaQueryWrapper<>();
        dlqw.eq(CourseDescription::getLinkId,courseListId);
        dlqw.eq(CourseDescription::getType,Constants.COURSE_DESCRIPTION_TYPE_LIST);
        List<CourseDescription>  courseDescriptions=courseDescriptionService.list(dlqw);
        if(CollectionUtil.isNotEmpty(courseDescriptions)){
            courseListResponse.setDescription(StrUtil.isBlank(courseDescriptions.get(0).getDescription()) ? "" : courseDescriptions.get(0).getDescription());
        }
        return courseListResponse;
    }

    @Override
    public CourseListResponse detail(Integer courseListId) {
        CourseList courseList=getById(courseListId);
        CourseListResponse courseListResponse=new CourseListResponse();
        BeanUtil.copyProperties(courseList,courseListResponse);
        //获取富文本详情
        LambdaQueryWrapper<CourseDescription> dlqw=new LambdaQueryWrapper<>();
        dlqw.eq(CourseDescription::getLinkId,courseListId);
        dlqw.eq(CourseDescription::getType,Constants.COURSE_DESCRIPTION_TYPE_LIST);
        List<CourseDescription>  courseDescriptions=courseDescriptionService.list(dlqw);
        if(CollectionUtil.isNotEmpty(courseDescriptions)){
            courseListResponse.setDescription(courseDescriptions.get(0).getDescription());
        }
        return courseListResponse;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Integer courseListId) {
        CourseList courseList=getById(courseListId);
        this.removeById(courseListId);
        LambdaQueryWrapper<CourseDescription> lqw=new LambdaQueryWrapper<>();
        lqw.eq(CourseDescription::getLinkId,courseListId);
        lqw.eq(CourseDescription::getType,Constants.COURSE_DESCRIPTION_TYPE_LIST);
        courseDescriptionService.remove(lqw);
        // 更新课程的章节数
        LambdaUpdateWrapper<Course> courseLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        courseLambdaUpdateWrapper.setSql(StrUtil.format("list_count = list_count - {}", 1));
        courseLambdaUpdateWrapper.eq(Course::getId, courseList.getCourseId());
        courseService.update(courseLambdaUpdateWrapper);
        return true;
    }
}

